<template>
  <div class="circle">
    <canvas id="canvas" width="320" height="320"></canvas>
  </div>
</template>

<script>
  export default {
    props: {
      colors: {
        type: Array,
        default: function () { return ['#3faef9', '#0069df', '#ff6c00'] }
      },
      amounts: {
        type: Array,
        default: function () { return [0, 0, 0] }
      }
    },
    mounted () {
      const canvas = document.getElementById('canvas')
      const ctx = canvas.getContext('2d')

      const midWidth = parseInt(canvas.width) / 2
      const midHeight = parseInt(canvas.height) / 2
      const randomAngle = Math.random() * 2 // 随机开始绘制的角度

      const width = 40 // 圆环的大小
      const circleRadius = 140 // 圆的半径

      // 计算绘制的角度
      let totalMoney = 0
      this.amounts.forEach((item) => {
        totalMoney += item
      })

      const angles = []
      this.amounts.forEach((item) => {
        angles.push(item / totalMoney * 2)
      })

      // 画部分的圆环
      const drawArc = (width, color, circleRadius, startAng, endAng) => {
        ctx.beginPath()
        ctx.lineWidth = width
        ctx.strokeStyle = color
        ctx.arc(midWidth, midHeight, circleRadius, startAng * Math.PI, endAng * Math.PI)
        ctx.stroke()
      }

      // 剪切线
      const drawLine = (angle) => {
        ctx.rotate(angle * Math.PI)
        ctx.moveTo(0, 0)
        ctx.lineTo(160, 0)
        ctx.stroke()
      }
      // 如果总资产为0画一个灰色的圆环
      if (totalMoney === 0) {
        drawArc(width, '#e5e5e5', circleRadius, 0, 2)
        return
      }

      // 绘制百分比的圆环
      drawArc(width, this.colors[0], circleRadius, randomAngle, randomAngle + angles[0])
      drawArc(width, this.colors[1], circleRadius, randomAngle + angles[0], angles[0] + angles[1] + randomAngle)
      drawArc(width, this.colors[2], circleRadius, angles[0] + angles[1] + randomAngle, 2 + randomAngle)

      // 裁剪
      ctx.globalCompositeOperation = 'destination-out'

      // 准备线的状态
      ctx.beginPath()
      ctx.lineWidth = 4
      ctx.strokeStyle = '#fff'
      ctx.translate(midWidth, midHeight)

      drawLine(angles[0] + randomAngle)
      drawLine(angles[1])
      drawLine(angles[2])
    }
  }
</script>

<style lang='scss' scoped>
  .circle {
    #canvas {
      width: 320px;
      height: 320px;
    }
  }
</style>
